package com.IClass.IActivity;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.IClass.IBlogCommentListAdapter;
import com.IClass.IClassApi;
import com.IClass.IGalleryImageAdapter;
import com.IClass.ImageUtil;
import com.IClass.iBlogCommentListAdapter2;
import com.IClass.App.IClass;
import com.IClass.App.R;
import com.IClass.Server.AppJsonDefine.GenJavaCode.homeblogcomment;
import com.IClass.image.AsynImageLoader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Gallery;
import android.widget.ListView;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class IBlogDiscussActivity extends Activity {

	public String mblogid;
	public static int GETBLOG_COMMENT_OK = 100000;
	public ImageView returnbutton;
	public ImageView userinfo;
	public TextView blogtitle;
	public ImageView blogimage;
	public TextView blogtext;
	public ExpandableListView commentlistview;
	public Context context;
	public AsynImageLoader mImageAsynLoader;
	public EditText commentedittext; 
	public Button sendcomment;
	public Button commentlistbtn;
	public boolean clickcommentlist;
	public Gallery gallery;
	public WebView webview;
	
	private Handler mHandler = new Handler();  
	private Map<String, Object> blogdata;
	
	public ProgressDialog progressDialog;
	public String commenttext;
	public String userid;
	
	public Handler mhandle = new Handler();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.iask_blogdisucss2_layout);
		mblogid = (String)this.getIntent().getStringExtra("blogid");
		blogdata = IClass.gethotblogsmap().get(mblogid);
		
		//returnbutton = (ImageView)findViewById(R.id.return_button);  
		//userinfo = (ImageView)findViewById(R.id.userinfo);
		//blogtitle = (TextView)findViewById(R.id.blogtitle);
		//blogimage = (ImageView)findViewById(R.id.blogimage);
		//blogtext = (TextView)findViewById(R.id.blogtext);
		//commentlistview = (ExpandableListView)findViewById(R.id.commentlist);
		
		commentedittext = (EditText) findViewById(R.id.commentedittext);
		sendcomment = (Button) findViewById(R.id.button1);
		commentlistbtn = (Button) findViewById(R.id.commentlist);
		context = this;
		
		
		//gallery = (Gallery) findViewById(R.id.gallery1);
		List<String> galleryimageslist = new ArrayList<String>();
		galleryimageslist.add(IClassApi.SERVER_HOST + blogdata.get("image_1"));
		
		webview = (WebView) findViewById(R.id.webView1);
		String title = "<h4>{actor} 发表了新日志</h4><hr/>";//(String)blogdata.get("title_template");
		title = title.replace("{actor}", (String)blogdata.get("username"));
		//title = title.replace("{userimage}", "<img src=\"" + (String)blogdata.get("userimage") + "\"/>");
		
		String body_template = (String)blogdata.get("body_template");
		body_template = "<h4 style=\"text-align:center;\">{subject}</h4>{summary}</br>";
		body_template = body_template.replace("{subject}", (String)blogdata.get("subject"));
		body_template = body_template.replace("{summary}", (String)blogdata.get("summary"));
		
		String image_template = "<p align=\"center\"><img src=\"{image_url}\"  border=\"0\" onClick=\"window.demo.clickimage()\" align=\"center\"></p>";
		image_template = image_template.replace("{image_url}",  IClassApi.SERVER_HOST +  (String)blogdata.get("image_1"));
		
		String data = "<html><body>" + title + image_template + body_template + "</body></html>";
		webview.getSettings().setDefaultTextEncodingName("utf-8") ;
		webview.getSettings().setJavaScriptEnabled(true);
		
		webview.addJavascriptInterface(new Object() {  
            public void clickimage() {  
                mHandler.post(new Runnable() {  
                    public void run() {  
        				final View vPopupWindow = getLayoutInflater().inflate(R.layout.iask_blogpictureview,null,false);                               // 加载popupWindow的布局文件     
        				//vPopupWindow.setBackgroundColor(Color.GREEN);
        				
        				final PopupWindow pw = new PopupWindow(vPopupWindow, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
        				pw.setContentView(vPopupWindow);
        				
        				
        				ImageView imageview = (ImageView) vPopupWindow.findViewById(R.id.imageView1);
        				String bigpictureurl = IClassApi.SERVER_HOST +  (String)blogdata.get("image_1");
        				//(String) arg1.getTag();
        				//http://ltfll.gicp.net:8085/data/attachment/album/201205/17/181253za22ntxox14tzntn.jpg
        					//http://ltfll.gicp.net:8085/data/attachment/album/201205/17/181253za22ntxox14tzntn.jpg.thumb.jpg
        				bigpictureurl = bigpictureurl.substring(0, bigpictureurl.lastIndexOf(".thumb.jpg"));
        				
        				imageview.setTag(bigpictureurl);
        				mImageAsynLoader.loadBitmap(imageview,  ImageUtil.getBitmapById(context, R.drawable.icon_3_n));
        				vPopupWindow.setOnKeyListener(new OnKeyListener() 
        				{
        			            
        			            @Override
        			            public boolean onKey(View v, int keyCode, KeyEvent event) {
        			                // TODO Auto-generated method stub
        			                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK)
        			                	pw.dismiss();
        			                return false;
        			            }
        			        });
        				vPopupWindow.setOnClickListener(new OnClickListener()
        				{
        
        					@Override
        					public void onClick(View v) {
        						// TODO Auto-generated method stub
        						pw.dismiss();
        					}
        					
        				});
        				pw.showAtLocation(webview, Gravity.CENTER, 0, 0);// 以屏幕中心为参照，不偏移
                    }  
                });  
            }  
        }, "demo");  
		
		webview.loadData(data, "text/html", "utf-8"); 

		new Thread(){
    		@Override
            public void run() {
    			List<homeblogcomment> commentlist = IClass.getBlogcomments().get(mblogid);
    			if(commentlist == null)
    				IClass.classapi.GetBlogCommont(mblogid);
    			
    		}
    	}.start();
		mImageAsynLoader = new AsynImageLoader();

		sendcomment.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v) {
				// FIXME Auto-generated method stub
				
				SharedPreferences  share = context.getSharedPreferences("IClass", MODE_PRIVATE);  
		        userid = share.getString("userid", "0");
		        
		        if(userid == "0")
		        {
					Intent mainIntent = new Intent(IBlogDiscussActivity.this,IRegisterActivity.class); 
	                startActivity(mainIntent);    //启动Main界面
	                
		        	return;
		        }
		        commenttext = commentedittext.getText().toString();
		        
		        if(commenttext != null && commenttext.length() > 0)
		        {
		        	mhandle.post(new Runnable() {
						@Override
						public void run() {
							progressDialog = ProgressDialog.show(IBlogDiscussActivity.this, "请稍等...","发送评论...", true);
						}

					});
		        	
				        
					//IClass.classapi.SendBlogCommentText(mblogid, userid, commenttext);
		        	//new SendCommentTextThread(mblogid, userid, commenttext).start();	
		        	new Thread(){
		        		@Override
			            public void run() {
		        			String result = IClass.classapi.SendBlogCommentText(mblogid, userid, commenttext);
		        			if(result != null && !result.equals(""))
		        			{
		        				List<homeblogcomment> commentlist = IClass.getBlogcomments().get(mblogid);
		        				JSONObject jsonobj;
								try {
									jsonobj = new JSONObject(result);
									
									homeblogcomment b = new homeblogcomment();
									b.uid =  jsonobj.getString("uid");
									b.dateline = jsonobj.getString("dateline");
									b.author = jsonobj.getString("author");
									b.authorid = jsonobj.getString("authorid");
									b.cid = jsonobj.getString("cid");
									b.id = jsonobj.getString("id");
									b.idtype = jsonobj.getString("idtype");
									b.message = jsonobj.getString("message");
									b.avatarurl = jsonobj.getString("avatarurl");
									
									commentlist.add(b);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								
								
		        			}
		        			
		        			
		        			mhandle.post(new Runnable() {
								@Override
								public void run() {
									progressDialog.dismiss();
				        			
				        			Toast.makeText(IBlogDiscussActivity.this, "回复成功...", Toast.LENGTH_SHORT).show();
				        			
				        			
				        			
				        			
								}

							});
		        			
		        			
		        		}
		        	}.start();
					
		        }
		       
				
			}

		}
		);
		//查看评论列表
		commentlistbtn.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				List<homeblogcomment> commentlist = IClass.getBlogcomments().get(mblogid);
				if(commentlist != null)
				{
					final View vPopupWindow = getLayoutInflater().inflate(R.layout.comment_list,null,false);                               // 加载popupWindow的布局文件     
					//vPopupWindow.setBackgroundColor(Color.BLACK);
					
					WebView commentview = (WebView) vPopupWindow.findViewById(R.id.webView1);
					
					commentview.getSettings().setDefaultTextEncodingName("utf-8") ;
					commentview.getSettings().setJavaScriptEnabled(true);
					String data = "<html><body><table rules=\"rows\" cellpadding=\"5\" width=\"100&#37\">";
					
					SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
					
					for(homeblogcomment h:commentlist)
					{
						data = data + "<tr>";
						data = data + "<td valign=\"top\" width=\"10&#37\">" + "<img src=" + IClassApi.SERVER_HOST + "uc_server/"+ h.avatarurl + "></img>" + "</td>";
						data = data + "<td>" + h.author + ":" + h.message + "</br>" + "<font size=\"1\" color=\"gray\">" + f1.format(new Date(Long.valueOf(h.dateline) * 1000)) + "</font></td></hr>";
						data = data + "</tr>";
					}
					data = data + "</table></body></html>";	
					commentview.loadData(data, "text/html", "utf-8"); 
//					ListView commentlistview = (ListView) vPopupWindow.findViewById(R.id.comment_list);
//					iBlogCommentListAdapter2 listItemAdapter = new iBlogCommentListAdapter2(context,commentlist);
//					
//					commentlistview.setAdapter(listItemAdapter);
					final PopupWindow pw = new PopupWindow(vPopupWindow, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
					pw.setContentView(vPopupWindow);
//					
//					
//					
					pw.showAtLocation(v, Gravity.CENTER, 0, 0);// 以屏幕中心为参照，不偏移
					
					vPopupWindow.setFocusable(true);
					vPopupWindow.setFocusableInTouchMode(true);
				        //监听Key触发事件，使得点击Back键的时候，PopupWindow消失
					vPopupWindow.setOnKeyListener(new OnKeyListener() 
					{
				            
				            @Override
				            public boolean onKey(View v, int keyCode, KeyEvent event) {
				                // TODO Auto-generated method stub
				                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK)
				                	pw.dismiss();
				                return false;
				            }
				        });
				}
				else
				{
					Toast.makeText(IBlogDiscussActivity.this, "加载评论中...", Toast.LENGTH_LONG).show();
				}
				
			}
			
		});
		
		
		//blogtitle.setText((String)blogdata.get("summary"));
		
		//blogimage.setTag(IClassApi.SERVER_HOST + blogdata.get("image_1"));
		//blogtext.setText((String)blogdata.get("subject"));
		//mImageAsynLoader.loadBitmap(blogimage, ImageUtil.getBitmapById(context, R.drawable.blogimage));
		
	}
	
	
}
